<template>
  <el-select
    style="width:100%"
    v-model="val"
    @change="change"
    :collapse-tags="collapseTags"
    :disabled="disabled"
    :clearable="clearable"
    :filterable="filterable"
    :multiple="multiple"
    :placeholder="holder"
  >
    <el-option
      v-for="item in items"
      :key="item.value"
      :label="item.name"
      :value="item.value"
      :disabled="item.disabled"
    ></el-option>
  </el-select>
</template>
<script>
export default {
  props: {
    url: {
      type: String,
      default: ""
    },
    value: {
      type: [String, Number],
      default: ""
    },
    type: {
      type: String,
      default: "dict"
    },
    dictCode: {
      type: String,
      default: ""
    },
    holder: {
      type: String,
      default: "请选择"
    },
    autoLoad: {
      type: Boolean,
      default: true
    },
    clearable: {
      type: Boolean,
      default: true
    },
    multiple: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    collapseTags: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      default: "htk"
    }
  },
  data() {
    return {
      val: "",
      apiUrl: "",
      items: []
    };
  },
  created() {
    if (!this.autoLoad) {
      return;
    }
    this.load();
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        if (this.multiple) {
          if (!v) {
            this.val = [];
          } else {
            if (this.value.indexOf(",") != -1) {
              this.val = v.split(",");
            } else {
              this.val = [v];
            }
          }
        } else {
          this.val = v;
        }
      }
    }
  },
  methods: {
    change(v) {
      let realVal = v;
      if (this.multiple) {
        realVal = v.toString();
      }
      this.$emit("input", realVal);
      let valObj = this.items.find(item => {
        return v == item.value;
      });
      this.$emit("changeObj", valObj);
    },
    load() {
      let me = this;
      if (me.type == "dict") {
        me.apiUrl = "sysDictData/getForSelect/";
        me.$http.ajax({
          url: me.apiUrl + me.dictCode,
          success(res) {
            me.items = res;
          }
        });
      } else {
        if (!me.url) {
          console.error("请配置select的URL");
          return;
        }
        me.$http.ajax({
          url: me.url,
          code: me.code,
          success(res) {
            me.items = res;
            me.$nextTick(() => {
              me.$emit("loaded", me.value);
            });
          }
        });
      }
    }
  }
};
</script>
<style scoped>
</style>


